package com.qf.interceptor;


import com.qf.annotation.NoLoginCheck;
import com.qf.constant.CommonConstant;
import com.qf.exception.CommonException;
import com.qf.utils.JwtUtils;
import com.qf.utils.RedisUtil;
import com.qf.utils.UserUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author ljw
 * @version 1.0
 * @Date 2024/12/10 15:36
 */
@Component
public class AuthorizationInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisUtil redisUtil;

    // 登录成功后，将token发送给前端
    // 前端发送请求时，需要将token放到请求头中，发送给后台

    // 本例，从Authorization这个请求头中获取token值
    // 注意,需要将前端的请求头改变为Authorization
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){

        //控制方法会封装为HandlerMethod对象
        if(handler instanceof HandlerMethod){
            HandlerMethod handlerMethod=(HandlerMethod) handler;
            Method method = handlerMethod.getMethod();
            //判断这方法是否使用指定注解
            boolean ret = method.isAnnotationPresent(NoLoginCheck.class);
            if(ret){
                return true;
            }
            String token = request.getHeader(CommonConstant.TOKEN);
//            User user = redisUtil.getCacheObject(String.format(RedisKeyEnum.KEY_LOGIN.getKey(),token));
            if (token == null || "".equals(token)) {
                throw new CommonException(CommonConstant.NOTAUTHORIZATION,"无效令牌,重新登录");
            }
            try {
                Claims claims = JwtUtils.parseJWT(token);
                Integer id =(Integer) claims.get("id");
                //将用户id取出来
                UserUtils.setId(id);
            }catch (Exception e){
                throw new CommonException(CommonConstant.NOTAUTHORIZATION,"身份信息失效,重新登录");
            }
//            if (user == null) {
//                throw new CommonException(CommonConstant.NOTAUTHORIZATION,"身份信息失效,重新登录");
//            }
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //控制层接口从ThreadLocal 中删除当前用户id（本质从当前线程的ThreadLocalMap对中删除）
        UserUtils.remove();
    }
}
